
//
//  UINavigationController+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/23.
//


public extension UINavigationController {
    
    // MARK: - 基本导航方法
    public func firstEqualSelf() -> Bool {
        if let vc = viewControllers.first,vc == self {
            return true
        }
        return false
    }
    /// 返回到导航栈的第一个控制器
    public func popToFirstViewController(animated: Bool = true) {
        guard viewControllers.count > 1 else { return }
        popToViewController(viewControllers[0], animated: animated)
    }
    
    /// 返回到导航栈的倒数第二个控制器（上一个页面）
    public func popToPreviousViewController(animated: Bool = true) {
        guard viewControllers.count > 1 else { return }
        let previousIndex = viewControllers.count - 2
        popToViewController(viewControllers[previousIndex], animated: animated)
    }
    
    /// 返回到指定类型的第一个控制器
    public func popToFirstViewController<T: UIViewController>(ofType type: T.Type, animated: Bool = true) -> Bool {
        if let targetVC = viewControllers.first(where: { $0 is T }) as? T {
            popToViewController(targetVC, animated: animated)
            return true
        }
        return false
    }
    
    /// 返回到指定类型的所有控制器之前（保留该类型及之后的控制器）
    public func popToBeforeViewController<T: UIViewController>(ofType type: T.Type, animated: Bool = true) -> Bool {
        guard let targetIndex = viewControllers.firstIndex(where: { $0 is T }) else { return false }
        guard targetIndex > 0 else { return false }
        
        let previousVC = viewControllers[targetIndex - 1]
        popToViewController(previousVC, animated: animated)
        return true
    }
    
    // MARK: - 安全导航方法
    
    /// 安全返回到指定索引的控制器
    public func popToViewController(at index: Int, animated: Bool = true) -> Bool {
        guard index >= 0, index < viewControllers.count else { return false }
        popToViewController(viewControllers[index], animated: animated)
        return true
    }
    
    /// 移除指定类型的所有控制器（除了第一个匹配的）
    public func removeAllAfterFirst<T: UIViewController>(ofType type: T.Type) {
        guard let firstIndex = viewControllers.firstIndex(where: { $0 is T }) else { return }
        
        let controllersToKeep = Array(viewControllers.prefix(firstIndex + 1))
        viewControllers = controllersToKeep
    }
    
    /// 移除指定类型之前的所有控制器
    public func removeAllBeforeFirst<T: UIViewController>(ofType type: T.Type) {
        guard let firstIndex = viewControllers.firstIndex(where: { $0 is T }) else { return }
        
        let controllersToKeep = Array(viewControllers.suffix(from: firstIndex))
        viewControllers = controllersToKeep
    }
}
